import React, { Component } from 'react'
import { Checkbox, Row, Col } from 'antd'

export default class CheckItem extends Component {
  onChange = (checked, id, children) => {
    const { parent, data, onChange } = this.props
    data.checked = checked
    id === data.id && notifyChildren(checked, children)
    if (parent) {
      // parent.checked = (checked ? parent.children.every(v => v.checked === checked) : false)
      parent.checked = (checked ? true : parent.children.some(v => v.checked))
      onChange && onChange(parent.checked, id, parent.children)
    } else {
      onChange && onChange()
    }
  }

  render() {
    const { data } = this.props
    const { id, children, name, checked } = data
    return <div className="treeData-list-item">
      <Checkbox
        checked={checked}
        onChange={(e) => this.onChange(e.target.checked, id, children)}
      >
        {name}
      </Checkbox>
      {
        children && children.length > 0 &&
          <div className="treeData-list-child">
            <Row gutter={[8, 8]}>
              {
                children.map(item => {
                  return <Col span={12} key={item.id}>
                    <CheckItem
                      data={item}
                      parent={data}
                      onChange={this.onChange}
                    />
                  </Col>
                })
              }
            </Row>
          </div>
      }
    </div>
  }
}

const notifyChildren = (checked, children) => {
  (children || []).map(v => {
    v.checked = checked
    v.children && v.children.length > 0 && notifyChildren(checked, v.children)
  })
}
